package com.example.day1.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.day1.common.BaseContent;
import com.example.day1.common.R;
import com.example.day1.entity.AddressBook;
import com.example.day1.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    //保存用户信息
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        //下面的每个操作方法都需要先执行给address设置一个id值，容易操作和保存数据库
        addressBook.setUserId(BaseContent.getCurrentId());
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    //修改用户默认信息
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){

        LambdaUpdateWrapper<AddressBook> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        objectLambdaUpdateWrapper.eq(AddressBook::getUserId, BaseContent.getCurrentId());
        objectLambdaUpdateWrapper.set(AddressBook::getIsDefault,0);
        //先将所有的数据默认值先设置为0
        addressBookService.update(objectLambdaUpdateWrapper);

        //在设置指定的对象的默认地址为1
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);

    }
    //根据id查数据
    @GetMapping
    public R get(@PathVariable("id") Long id){
        AddressBook byId = addressBookService.getById(id);
        if(byId!=null){
            return R.success(byId);
        }
        return R.error("没有找到对象");
    }
    //查询用户默认信息
    @GetMapping("default")
    public R<AddressBook > getDefault(){
        LambdaQueryWrapper<AddressBook> objectLambdaQueryWrapper =new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        objectLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContent.getCurrentId());
        AddressBook one = addressBookService.getOne(objectLambdaQueryWrapper);
        if(one!=null){
            return R.success(one);
        }
        return R.error("没有找到对象");
    }
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        addressBook.setUserId(BaseContent.getCurrentId());
        LambdaQueryWrapper<AddressBook> objectLambdaQueryWrapper =new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(null!=addressBook.getUserId(),AddressBook::getUserId,addressBook.getUserId());
        objectLambdaQueryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(objectLambdaQueryWrapper);
        return R.success(list);

    }
}
